package com.lsiyun.sync_file.old;

import java.io.*;
import java.net.Socket;

/**
 * 网络文件类
 */
public class NetFile implements Serializable {
    File file;

    /**
     * 文件路径（包括文件名）
     */
    private String path;

    private String name;

    private boolean exists;

    private boolean isDirectory;
    private boolean isFile;
    private long lastModified;
    private NetFile[] files;

    public boolean exists() {
        return exists;
    }

    public boolean isDirectory() {
        return isDirectory;
    }

    public boolean isFile() {
        return isFile;
    }

    public long lastModified() {
        return lastModified;
    }

    public NetFile[] listFiles(Socket socket) throws IOException, ClassNotFoundException {
        socket.getOutputStream().write(4);
        new ObjectOutputStream(socket.getOutputStream()).writeObject(file);
        return (NetFile[]) new ObjectInputStream(socket.getInputStream()).readObject();
    }

    public NetFile(String pathname) {
        file = new File(pathname);
        init();
    }

    private void init() {
        if (file == null) {
            return;
        }

        exists = file.exists();
        isDirectory = file.isDirectory();
        isFile = file.isFile();
        files = new NetFile[file.list() == null ? 0 : file.list().length];
        for (int i = 0; i < files.length; i++) {
            NetFile netFile = new NetFile(file.list()[i]);
            files[i] = netFile;
        }
        lastModified = file.lastModified();
        name = file.getName();
        path = file.getPath();
    }

    public NetFile(String parent, String child) {
        file = new File(parent, child);
        init();
    }

    public NetFile(NetFile parent, String child) {
        file = new File(parent.file.getPath(), child);
        init();
    }

    public String getName() {
        return name;
    }

    public void mkdirs(Socket socket) throws IOException {
        socket.getOutputStream().write(1);
        new ObjectOutputStream(socket.getOutputStream()).writeObject(file);
    }

    public void delete(Socket socket) throws IOException {
        socket.getOutputStream().write(2);
        new ObjectOutputStream(socket.getOutputStream()).writeObject(file);

    }

    public void setLastModified(Socket socket, long modifiedTime) throws IOException {
        socket.getOutputStream().write(3);
        new ObjectOutputStream(socket.getOutputStream()).writeObject(file);
        new ObjectOutputStream(socket.getOutputStream()).writeObject(modifiedTime);
    }
}
